<?php

class ProductImport extends ImportBase
{
	private $product_table = 'products';
	private $products_description = 'products_description';
	private $products_categories = 'products_to_categories';
	
	private $website_id;
	
	private $default_product_type = 'simple';
	private $default_tax_class;
	private $default_attribute_set;
	
	protected $db;
	
	private $api;
	
	public function __construct()
	{
		global $config;
		//echo "{$config['db_host']},{$config['db_user']},{$config['db_pass']},{$config['db_name']}";
		$this->set_s_db( $config['db_host'],$config['db_user'],$config['db_pass'],$config['db_name'] );
		
		$this->api = Mage::getModel('catalog/category_api');
		
		$this->website_id = $config['website_id'];
		
		$this->default_tax_class = $config['default_tax_class'];
		$this->default_attribute_set = $config['default_attribute_set'];
		
		$this->db = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
		$this->import_num = 100;
		parent::__construct();
	}
	
	function run()
	{
		$all_products = $this->getAllProduct();
		foreach( $all_products as $_product ){
			$this->import_product( $_product['products_id'] );
			$this->transation_commit();
			
		}
	}
	
	protected function getAllProduct()
	{
		$query = "select * from `{$this->product_table}` p left join `{$this->log_table}` log ON p.products_id = log.org_product_id where log.org_product_id is null limit 2000";
		$this->s_db->query( $query );
		echo $query;
		return $this->s_db->af();
	}
	
	
	private function import_product( $product_id )
	{
		static $counter = 0;
		global $config;
		
		$product_exist = $this->read_log( array( 'org_product_id' => $product_id ) );
		if( !$product_exist ){
			$product_data = $this->read_product( $product_id );
			
			echo 'sku = '.$product_data['default']['sku'].'<br>';
			
			if( !empty( $product_data['default']['sku'] ) ){
				if( $this->is_entity_id_exist( $product_data['default']['zencart_id'] ) )
					$new_product_id = $product_data['default']['zencart_id'];
				else
					$new_product_id = Mage::getModel("magicimport/magicimport_product_eav")->setSkuField('sku')->createEntity( $product_data['default']['sku'],10,$product_data['default']['attribute_set_id'],$product_data['default']['zencart_id'] );
				
				if( $new_product_id ){
					echo 'create new ID:'.$new_product_id.'<br>';
					Mage::getModel("magicimport/magicimport_product_eav")->setSkuField('sku')
								->update( $new_product_id,$product_data['default'],0 );
					
				}
			}			
		
			$this->log( array( 'org_product_id' => $product_id,'product_id' => $new_product_id ) );
						
			if( $config['enable_attribute_import_as_custom_options'] ){
				$this->import_attributes_as_custom_options( $new_product_id,$product_id );
			}
			
		}
		
	}
	
	private function is_entity_id_exist( $entity_id )
	{
		$entity_id = $this->db->fetchOne ( "select entity_id from catalog_product_entity where entity_id = '{$entity_id}'" );
		if ($entity_id) {
			return true;
		}else return false;
	}
	
	
	
	public function read_product( $product_id )
	{
		global $config;
		$product_data = array();
		
		$store_views = $this->allStoreViews();
		
		$query = "select p.*,pd.*,m.manufacturers_name from `{$this->product_table}` p join `{$this->products_description}` pd ";
		$query.= " on p.products_id = pd.products_id left join manufacturers m on p.manufacturers_id=m.manufacturers_id where p.products_id = '{$product_id}'";
		
		$this->s_db->query( $query );
		
		$product_rows = $this->s_db->af();
		
		$lang2storeviews = array_flip( $config['store_views'] );
		foreach( $product_rows as $_product ){
			if( isset( $lang2storeviews[ $_product['language_id'] ] ) && $_product['language_id'] != $config['default_lang'] )
				$product_data[ $this->getStoreIdByCode( $lang2storeviews[ $_product['language_id'] ] ) ] = $this->format_base_data( $_product );
			else if( $_product['language_id'] == $config['default_lang'] )
				$product_data[ 'default' ] = $this->format_base_data( $_product );
		}
		
		return $product_data;
	}
	
	private function format_base_data( $data )
	{
		global $config;
		$formated_data = array();
		
		if( $data['language_id'] == $config['default_lang'] ){
			$formated_data['type'] = $this->default_product_type;
			$formated_data['sku'] = trim($data['products_model']);
			
			$formated_data['tax_class_id'] = $this->default_tax_class;
			$formated_data['status'] = $data['products_status'] === 0 ? 2:1;
			
			$tier_price = $this->get_product_tier_price( $data );
			if( count( $tier_price ) )
				$formated_data['tier_price'] = $tier_price;
			
			$categires = $this->get_product_category_ids( $data['products_id'] );
						
			if( count( $categires ) )
				$formated_data['category_ids'] = $categires;
			
			
			$formated_data['name'] = $data['products_name'];
			$formated_data['url_key'] = $data['products_name'].' p '.$data['products_id'];
			$formated_data['price'] = $data['products_price'];
			$formated_data['weight'] = $data['products_weight'];
			$formated_data['description'] = $data['products_description'];
			$formated_data['qty'] = $data['products_quantity'];
			$formated_data['meta_title'] = $data['products_head_title_tag'];
			$formated_data['meta_description'] = $data['products_head_desc_tag'];
			$formated_data['meta_keyword'] = $data['products_head_keywords_tag'];
			$formated_data['brand'] = $data['manufacturers_name']?$data['manufacturers_name']:'';
			$formated_data['model_key'] = $data['model_key']?$data['model_key']:'';
			$formated_data['visibility'] = 4;
		
		}else{ // for other store view, only care the field below.
			if( $data['products_name'] ) $formated_data['name'] = $data['products_name'];
			if( $data['products_description'] ) $formated_data['description'] = $data['products_description'];
			if( $data['products_head_title_tag'] ) $formated_data['meta_title'] = $data['products_head_title_tag'];
			if( $data['products_head_desc_tag'] ) $formated_data['meta_description'] = $data['products_head_desc_tag'];
			if( $data['products_head_keywords_tag'] ) $formated_data['meta_keyword'] = $data['products_head_keywords_tag'];

		}
		
		$formated_data['attribute_set_id'] = $this->getAttributeSetId( $formated_data['sku'] );
		$formated_data['zencart_id'] = $data['products_id'];
		return $formated_data;
		
	}
	
	private function getAttributeSetId( $sku )
	{
		global $config;
		foreach( $config['attribute_set'] as $match => $_attribute_set_id ){
			if( eregi( $match,$sku ) )
				return $_attribute_set_id;
		}
		return $config['default_attribute_set'];
	}
	
	private function checkSKU( $sku )
	{
		$entity_id = $this->db->fetchOne ( "select entity_id from catalog_product_entity where sku = '{$sku}'" );
		if ($entity_id) {
			return $sku.'_'.rand(0,100000);
		}else return $sku;
	}
	
	protected function get_product_category_ids( $product_id )
	{
		$categy_ids = array();
		$query = "select log.* from `{$this->products_categories}` pc join `{$this->log_table}` log on pc.categories_id = log.org_category_id where products_id = '{$product_id}'";
		$this->s_db->query( $query );
		$categies = $this->s_db->af();
		foreach( $categies as $_category ){
			$categy_ids[] = $_category['category_id'];
		}
		
		return $categy_ids;
	}
	
	protected function get_product_tier_price( $product_data )
	{
		
		$tier_price_data = array();
		for( $i=1;$i<12;$i++ ){
			$field_price = 'products_price'.$i;
			$field_qty = 'products_price'.$i.'_qty';
			if( $product_data[ $field_price ] > 0 && $product_data[ $field_qty ] > 0 ){
				$tier_price_data[] = array( 'website_id'=>0,'cust_group'=>32000,'price_qty'=>$product_data[ $field_qty ],'price'=>$product_data[ $field_price ] );
			}
		}
		return $tier_price_data;
	}
	
	
	public function import_attributes_as_custom_options( $product_id,$os_product_id )
	{
		global $config;
		$lang2storeviews = array_flip( $config['store_views'] );
		$custom_options = array();
		
		//find attribute title
		$query = "select * from products_attributes where products_id = '{$os_product_id}' limit 1";
		$this->s_db->query( $query );
		if( $this->s_db->num_rows() ){
			$this->s_db->next_record();
			$option_id = $this->s_db->f("options_id");
			$option_value_id = $this->s_db->f("options_values_id");
			
			//get option title
			$query = "select * from products_options_text where products_options_text_id = '$option_id'";
			$this->s_db->query( $query );
			if( $this->s_db->num_rows() ){
				$options_text = $this->s_db->af();
				foreach( $options_text as $option_title ){
					if( isset( $lang2storeviews[ $option_title['language_id'] ] ) && $this->getStoreIdByCode( $lang2storeviews[ $option_title['language_id'] ] ) ){
						$custom_options[ $this->getStoreIdByCode( $lang2storeviews[ $option_title['language_id'] ] ) ]['title'] = $option_title['products_options_name'];
						//get option values.
						$query = "select pov.products_options_values_name,pov.options_values_price from products_attributes povtp join products_options_values pov ";
						$query .= "on povtp.options_values_id = pov.products_options_values_id where povtp.options_id = '$option_id' and povtp.products_id = '{$os_product_id}'";
						$query .= "and pov.language_id = '{$option_title['language_id']}'";
						
						$this->s_db->query( $query );						
						$custom_options[ $this->getStoreIdByCode( $lang2storeviews[ $option_title['language_id'] ] ) ]['value'] = $this->s_db->af();
					}
				}
				
				//use default's value if value is empty
				
				if( isset( $custom_options[ $config['default_store'] ] ) ){
					$default_store_customer_options = $custom_options[ $config['default_store'] ];
					foreach( $custom_options as $key => $var ){
						if( $key != $config['default_store'] ){
							foreach( $var['value'] as $value_key => $value_value ){								
								if( empty( $value_value['products_options_values_name'] ) ){
									$custom_options[ $key ]['value'][ $value_key ]['products_options_values_name'] = $default_store_customer_options['value'][ $value_key ]['products_options_values_name'];
								}
							}
						}
					}
				}
				
				
				
			}
			
			
			//try to import options into database directly
			if( !empty( $custom_options ) && isset( $custom_options[ $config['default_store'] ] ) ){
				
				$this->db->query ( "insert into `catalog_product_option` (`product_id`,`type`,`is_require`,`image_size_x`,`image_size_y`) 
					 values('{$product_id}','drop_down',1,0,0)");
										
					$magento_option_id = $this->db->lastInsertId ();
					
					
					
				foreach( $custom_options as $store_id => $option ){
					if( $store_id == $config['default_store'] ) $store_id = 0;
					$this->db->query ( "insert into `catalog_product_option_title` (`option_id`,`store_id`,`title`) 
					 values('{$magento_option_id}','{$store_id}','{$custom_options[ $config['default_store'] ]['title']}')");
					
					foreach( $option['value'] as $option_value ){
							
						$this->db->query ( "insert into `catalog_product_option_type_value` (`option_id`) 
						 values('{$magento_option_id}')");
						$magento_option_type_id = $this->db->lastInsertId ();	
						
						$this->db->query ( "insert into `catalog_product_option_type_title` (`option_type_id`,`store_id`,`title`) 
						 values('{$magento_option_type_id}','{$store_id}','{$option_value['products_options_values_name']}')");					
						
						$this->db->query ( "insert into `catalog_product_option_type_price` (`option_type_id`,`store_id`,`price`) 
					 	values('{$magento_option_type_id}','{$store_id}','{$option_value['options_values_price']}')");
						
					}

				}
				$this->db->query ( "update catalog_product_entity  set has_options = 1 where entity_id = '{$product_id}'");
			}
		}
		
	}
}